package point

import (
	"dev_gw/common"
	"fmt"

	"github.com/spf13/viper"
)

type Rs485XPortPoint struct {
	index    int
	ports    []string
	isConfig bool
}

func NewRs485XPortPoint() *Rs485XPortPoint {
	r := &Rs485XPortPoint{}
	v := viper.New()
	v.SetConfigName("config")
	v.SetConfigType("yaml")
	v.AddConfigPath(common.ConfigFilePath)
	err := v.ReadInConfig()
	if err != nil {
		fmt.Println("read config file failed, err -->", err)
		return r
	}
	r.isConfig = true
	r.ports = v.GetStringSlice("rs485Ports")
	return r
}

// func (s *Rs485XPortPoint) Get() any { return "/dev/ttyXRUSB" + string(rune(s.index+1)) }
func (s *Rs485XPortPoint) Get() any {

	fmt.Println("rs485 index -->", s.index)
	fmt.Println("is config --> ", s.isConfig)

	if !s.isConfig {
		v := viper.New()
		v.SetConfigName("config")
		v.SetConfigType("yaml")
		v.AddConfigPath(common.ConfigFilePath)
		err := v.ReadInConfig()
		if err != nil {
			fmt.Println("read config file failed, err -->", err)
			return ""
		}

		fmt.Println("rs485Ports -->", v.GetStringSlice("rs485Ports"))
		s.isConfig = true
		s.ports = v.GetStringSlice("rs485Ports")
	}

	if s.index > len(s.ports) {
		return ""
	}

	return s.ports[s.index-1]
}

func (s *Rs485XPortPoint) Set(...any) bool { return false }

func (s *Rs485XPortPoint) SetRoute(str string) PointInterface {
	s.index = int(str[len("rs485")]) - '0'
	return s
}
